package com.trafficsys.modules.owner.service.impl;

import com.alipay.api.AlipayApiException;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trafficsys.bean.AlipayBean;
import com.trafficsys.config.AlipayUtil;
import com.trafficsys.config.PayConfig;
import com.trafficsys.modules.entity.Ticket;
import com.trafficsys.modules.loginAndRegister.pojo.TicketAndRule;
import com.trafficsys.modules.owner.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

//import com.lish.bean.AlipayBean;
//import com.lish.config.AlipayUtil;
//import com.lish.service.PayService;

/* 支付服务 */
@Service
public class PayServiceImpl implements PayService {
	//注入阿里支付的配置类
	@Autowired
	private AlipayClient alipayClient;
	//注入读取配置文件的配置类
	@Autowired
	private PayConfig payConfig;
	@Override
	public HashMap<String, Object> aliPay(TicketAndRule ticketAndRule) {
		HashMap<String, Object> mmm = new HashMap<String, Object>();

		HashMap<String,Object> map = new HashMap<>();
		//订单编号
		map.put("out_trade_no", ticketAndRule.getCarNo()+ticketAndRule.getRuleId());

		//付款金额
		map.put("total_amount", ticketAndRule.getMoney());
		//商品名称
		map.put("subject", ticketAndRule.getCarNo()+"的罚单");
		//商品描述
		map.put("body", ticketAndRule.getCarNo()+"车辆车主，违反了第"+ticketAndRule.getRuleId()+"条交规："+ticketAndRule.getRuleName()+";"
		+"处以罚金"+ticketAndRule.getMoney()+"元。并扣 "+ticketAndRule.getCutScore()+"分的处罚。");

		try {
			//把请求参数转换成json字符串格式
			ObjectMapper objectMapper = new ObjectMapper();
			String jsonParams = objectMapper.writeValueAsString(map);

			// 设置阿里表单支付请求对象
			AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
			//设置参数
			alipayRequest.setBizContent(jsonParams);
			//设置支付成功返回的回调地址
			alipayRequest.setReturnUrl(payConfig.getReturnUrl());
			//设置异步回调的地址
			alipayRequest.setNotifyUrl(payConfig.getNotifyUrl());

			//获取支付宝支付响应对象
			AlipayTradePrecreateResponse alipayResponse = alipayClient.execute(alipayRequest);
			System.out.println(alipayResponse.toString());
			//将二维码支付地址 赋给hashMap 返回到前端生成支付二维码
			if(alipayResponse.isSuccess()){
				System.out.println("二维码支付地址="+alipayResponse.getQrCode());
				mmm.put("url",alipayResponse.getQrCode());
			}else{
				mmm.put("url","error");
			}

		}catch (Exception e){
			e.printStackTrace();
		}
		return mmm;
	}
}
